package com.erp.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.erp.Utils.ResponseModel;
import com.erp.Utils.getLoginUser;
import com.erp.entity.User;
import com.erp.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author CJ
 * @since 2021-08-14
 */
@Controller
@RequestMapping("/user")
@Api(value = "IndexController", tags = {"用户管理模块"})
@Slf4j
public class UserController {

    @Resource
    UserService userService;

    @GetMapping("/login")
    @ApiOperation("访问登陆页面")
    public String getLogin() {
        return "user/login";
    }

    @PostMapping("/login")
    @ApiOperation("登陆接口")
    @ResponseBody
    public ResponseModel checkLogin(@RequestBody JSONObject data,HttpServletRequest request, HttpServletResponse response) {
//        log.error("123");
        if (StrUtil.isEmpty((String) data.get("username"))
        || StrUtil.isEmpty((String) data.get("password"))){
            return ResponseModel.fail("参数缺少");
        }
        String username = Convert.toStr(data.get("username"));
        String password =  Convert.toStr(data.get("password"));
        User user =  userService.getOne(new QueryWrapper<User>()
        .eq("name",username));
        if (user != null){
            String newPassword = DigestUtil.md5Hex(password);
            if (!newPassword.equals(user.getPassword())){
                return ResponseModel.fail("密码错误");
            }else{
                HttpSession session = request.getSession();
                session.setAttribute("user", user.getName());
                session.setAttribute("userId", user.getId());
//                session.setMaxInactiveInterval(60*60); //设置session一个小时后过期
                return ResponseModel.success();
            }
        }else{
            return ResponseModel.fail("用户名不存在");
        }
    }
    //登出，移除登录状态并重定向的登录页
    @RequestMapping(value = "/loginOut", method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel loginOut(HttpServletRequest request){
        HttpSession session = request.getSession();
//        session.removeAttribute("user");
//        session.removeAttribute("userId");
        session.invalidate();
        return ResponseModel.success("退出成功,请重新登录");

    }
    // 修改密码
    @RequestMapping(value = "/changePwd",method = RequestMethod.GET)
    public ModelAndView changePwd(HttpServletRequest request){
        Map<String,Object> map = getLoginUser.getSession(request);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userName",map.get("userName"));
        modelAndView.addObject("userId",map.get("userId"));
        modelAndView.setViewName("user/changePwd");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping(value = "/change",method = RequestMethod.POST)
    public ResponseModel changePwd(@RequestBody Map<String,String> data){
        String userId = data.get("userId");
        String usedPwd = data.get("usedPwd");
        String newPwd = data.get("newPwd");
       if (StrUtil.isEmpty(userId) || StrUtil.isEmpty(usedPwd) ||
               StrUtil.isEmpty(newPwd)){
           return ResponseModel.fail("缺少参数");
       }
       User user = userService.getById(userId);
       // 效验旧密码
       String checkPassword = DigestUtil.md5Hex(usedPwd);
       if (!checkPassword.equals(user.getPassword())) {
           return ResponseModel.fail("抱歉，你输入的旧密码错误,无法执行修改操作");
       }
       String newPassword = DigestUtil.md5Hex(newPwd);
       user.setPassword(newPassword);
       boolean status = userService.updateById(user);
       if (status){
           return ResponseModel.success("修改成功");
       }else{
           return ResponseModel.fail("修改失败");
       }
    }

}
